<template>
  <view class="login-wrap">
    <view class="login-dialog" v-if="dialogType==='resetPwd'">
      <view class="title">
        设置新密码
      </view>
      <view class="tips">
        商户账号密码唯一，修改后会对手机号码对应的所有门店同时生效
      </view>
      <view class="input-box">
        <view class="input-item">
          <view class="label">
            重置密码
          </view>
          <input type="text" placeholder="请输入新的密码" class="input text-right" v-model="loginForm.npwd">
        </view>
        <view class="input-item">
          <view class="label">
            确认密码
          </view>
          <input type="text" placeholder="请再次输入新的密码" class="input text-right" v-model="loginForm.rpwd">
        </view>
        <view class="tips">
          <text class="text-red">*</text>
          <text>温馨提示：密码8-16位字符组成，必须包含字母、数字、特殊字符(@#$%^&<>?:\"_+,./-=[]!)其中一个</text>
        </view>
      </view>
      <view class="button-bar">
        <button class="button lg round full" @click="resetPwd">保存新密码</button>
      </view>
      <view class="tips">
        <text class="text-red">*</text>
        <text>记起密码，<text class="text-green" @click="changeDialogType('login')">立即登录</text> </text>
      </view>
    </view>
    <view class="login-dialog" v-if="dialogType==='findPwd'">
      <view class="title">
        找回密码
      </view>
      <view class="input-box">
        <view class="input-item">
          <view class="label">
            手机号码
          </view>
          <input type="text" placeholder="请输入11位手机号码" class="input text-right" v-model="loginForm.user_no"
            @change="changeMobile">
        </view>
        <view class="input-item">
          <view class="label">
            验证码
          </view>
          <input type="text" placeholder="请输入验证码" class="input" v-model="code">
          <button class="button light" @click="getCode" :disabled="canSendCode===false"><text class="margin-right"
              v-if="canSendCode===false">{{outTime||''}}</text> 获取验证码</button>
        </view>
      </view>
      <view class="button-bar">
        <button class="button lg round full" @click="verifyPhoneCode">下一步</button>
      </view>
      <view class="tips">
        <text class="text-red">*</text>
        <text>记起密码，<text class="text-green" @click="changeDialogType('login')">立即登录</text> </text>
      </view>
    </view>
    <view class="login-dialog" v-if="dialogType==='successReset'">
      <image src="/static/images/lock.png" mode="aspectFill" style="width: 23rem;height: 23rem;margin: 2rem;">
      </image>
      <view class="title">
        您已成功重置密码
      </view>
      <view class="tips">
        您的登录密码已重新设置，请妥善保管
      </view>
      <view class="input-box">
      </view>
      <view class="button-bar">
        <button class="button lg round full" @click="changeDialogType('login')">马上登录</button>
      </view>
    </view>
    <view class="login-dialog" v-else-if="dialogType==='login'">
      <view class="title">
        欢迎登录商户助手
      </view>
      <view class="tab-list">
        <view class="tab-item" :class="{active:tab.name===loginType}" v-for="tab in types"
          @click="changeLoginType(tab.name)">
          {{tab.name}}
        </view>
      </view>
      <view class="input-box">
        <view class="input-item">
          <text class="cuIcon-shop"></text>
          <uni-easyinput type="number" :trim="true" primaryColor="#38C09E" placeholder="请输入商家编号" class="input"
            v-model="loginForm.tenant" @change="changeTenant"></uni-easyinput>
        </view>
        <view class="input-item">
          <text class="cuIcon-mobile"></text>
          <uni-easyinput type="text" primaryColor="#38C09E" :placeholder="loginType==='账号登录'?'请输入账号':'请输入手机号'"
            class="input" v-model="loginForm.user_no" @change="changeMobile"></uni-easyinput>
          <!-- <input type="text" placeholder="请输入账号" class="input" v-model="loginForm.user_no"> -->
        </view>
        <view class="input-item" v-if="loginType==='账号登录'">
          <text class="cuIcon-lock"></text>
          <uni-easyinput type="password" primaryColor="#38C09E" placeholder="请输入密码" class="input"
            v-model="loginForm.pwd"></uni-easyinput>
          <!-- <input type="text" :password="!showPassword" placeholder="请输入密码" class="input" v-model="loginForm.pwd">
          <text class="cuIcon-attention uni-eye" :class="[!showPassword ? 'uni-eye-active' : '']"
            @click="changePassword"></text> -->
        </view>
        <view class="input-item" v-if="loginType==='账号登录'&&needImageCode">
          <text class="cuIcon-safe"></text>
          <uni-easyinput type="text" primaryColor="#38C09E" placeholder="请输入验证码" class="input" v-model="imageCode">
          </uni-easyinput>
          <image :src="codeImage" mode="aspectFill" class="image-code" @click="getImageCode"></image>
        </view>
        <view class="input-item" v-if="loginType==='手机登录'">
          <text class="cuIcon-safe"></text>
          <uni-easyinput type="number" primaryColor="#38C09E" placeholder="请输入验证码" class="input" v-model="code">
          </uni-easyinput>
          <!-- <input type="text" placeholder="请输入验证码" class="input" v-model="code"> -->
          <button class="button light" @click="getCode" :disabled="canSendCode===false"> <text class="margin-right"
              v-if="canSendCode===false">{{outTime||''}}</text> 获取验证码</button>
        </view>
      </view>
      <view class="check-box-bar flex justify-between">
        <u-checkbox-group v-model="isRemember" v-if="loginType==='账号登录'">
          <u-checkbox activeColor="#38C09E" label="记住账号" name="是" :size="2.4" :labelSize="2.4">
          </u-checkbox>
        </u-checkbox-group>
        <text v-else></text>
        <text v-if="loginType==='账号登录'" class="text-green flex align-center"
          @click="changeDialogType('findPwd')">忘记密码?</text>
      </view>
      <view class="tip-bar">
        <text class="text-gray ">点击登录即表示您同意</text> <text class="text-green">《商户合作协议》</text>
      </view>
      <view class="button-bar">
        <button class="button lg round full" @click="toLogin">立即登录</button>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    getUserMenus
  } from '@/common/api/index.js'
  export default {
    data() {
      return {
        codeImage: "",
        imageCode: "",
        needImageCode: false,
        dialogType: "login", // login,resetPwd.findPwd，successReset
        canSendCode: true,
        outTime: 60,
        showPassword: false,
        loginForm: {
          npwd: "", // 新密码
          rpwd: "", // 重复输入新密码
          "user_no": "", //账号 手机号
          "pwd": "", // 密码
          "terminal_type": "mt", //终端类型
          "tenant": "", //租户编号|店铺编号
        },
        saveLoginForm: {

        },
        phone: "", //手机号
        code: "", //验证码
        isRemember: [], //是否记住账号
        loginType: "账号登录",
        types: [{
            name: '账号登录',
          },
          {
            name: '手机登录',
          }
        ]
      }
    },
    onLoad() {
      let keys = ['$bx_auth_ticket', '$goodsList', '$loginUser', '$classifyList', '$memberList',
        '$staffList', '$curAssistant', '$curMember', '$memberSetup', '$srvCol'
      ]
      keys.forEach(key => {
        this.$store.commit('SET_STATE', {
          key: key,
          value: key && key.indexOf('ist') !== -1 || ['$srvCol'].includes(key) ? [] : null
        })
      })
      this.$store.commit('SET_LOGIN_STATE', false)
      uni.setStorageSync('persistData', null)
      let loginForm = uni.getStorageSync('loginForm')
      this.saveLoginForm = uni.getStorageSync('loginForm') || {}
      if (loginForm?.user_no) {
        this.loginForm = loginForm
        this.isRemember = ['是']
      }
    },
    methods: {
      async validImageCode() {
        if (!this.imageCode) {
          uni.showToast({
            title: '请输入图形验证码',
            icon: 'none'
          })
          return false
        }
        const url = `/sso/operate/srvsso_check_image_code`
        const req = [{
          "serviceName": "srvsso_check_image_code",
          "data": [{
            "image_code": this.imageCode
          }]
        }]
        const res = await this.$http.post(url, req)
        if (res?.data?.state === 'SUCCESS') {
          // this.accountLogin()
          return true
        } else {
          this.getImageCode()
          uni.showToast({
            title: res.data.resultMessage,
            icon: 'none'
          })
          return false
        }
      },
      async getImageCode() {
        const url = `/sso/operate/srvsso_image_code`
        const req = [{
          "serviceName": "srvsso_image_code"
        }]
        const res = await this.$http.post(url, req)
        let response = res?.data?.response
        if (Array.isArray(response) && response.length > 0) {
          let resData = response[0]
          if (resData?.response?.image) {
            this.codeImage = resData?.response?.image
          }
        }
      },
      changeMobile(e) {
        if ((this.dialogType === 'findPwd' || this.loginType === '手机登录') && e && Number(e) !== Math.abs(parseInt(e))) {
          uni.showToast({
            title: '手机号只能为数字',
            icon: 'none'
          })
          this.loginForm.user_no = ''
        }
      },
      changeTenant(e) {
        if (e && Number(e) !== Math.abs(parseInt(e))) {
          uni.showToast({
            title: '商家编号为4-16位数字',
            icon: 'none'
          })
          this.loginForm.tenant = ''
        }
      },
      // 校验手机号是否存在
      async verifyPhone() {
        const req = [{
          "serviceName": "srvsso_check_mobile",
          "data": [{
            "mobile": this.loginForm.user_no
          }]
        }]
        const url = `/sso/operate/srvsso_check_mobile`
        const res = await this.$http.post(url, req)
        if (res?.data?.state === 'SUCCESS') {
          return true
        } else {
          return false
        }
      },
      // 重置密码
      resetPwd() {
        const value = this.loginForm.npwd
        var par =
          /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&\<\>\?\:\"_+,\.\/-=\[\]\!\;\'*])[\da-zA-Z~!@#$%^&\<\>\?\:\"_+,\.\/-=\[\]\!\;\'*]{8,16}$/;
        if (!par.test(value)) {
          uni.showToast({
            title: "密码8-16位字符组成，必须包含字母、数字、特殊字符(@#$%^&<>?:\"_+,./-=[]!;')其中一个",
            icon: 'none'
          })
          return "密码8-16位字符组成，必须包含字母、数字、特殊字符(@#$%^&<>?:\"_+,./-=[]!;')其中一个";
        }
        // var reg =
        // 	/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[;~!@#$%^&\<\>\?\:\"_+,\.\/-=\[\]\!*])[\da-zA-Z~;!@#$%^&\<\>\?\:\"_+,\.\/-=\[\]\!*]{8,16}$/;
        // if (this.loginForm.npwd && !reg.test(this.loginForm.npwd)) {
        // 	uni.showToast({
        // 		title:'密码8-16位字符组成，必须包含字母、数字、特殊字符(;@#$%^&<>?:\"_+,./-=[]!)其中一个',
        // 		icon:'none'
        // 	})
        // 	return "密码8-16位字符组成，必须包含字母、数字、特殊字符(;@#$%^&<>?:\"_+,./-=[]!)其中一个";
        // }
        const req = [{
          "serviceName": "srvsso_reset_pwd",
          "data": [{
            "pwd": this.loginForm.npwd,
            "affirm_pwd": this.loginForm.rpwd
          }]
        }]
        const url = `/sso/operate/srvsso_reset_pwd`
        this.$http.post(url, req).then(res => {
          if (res?.data?.state === 'SUCCESS') {
            uni.showToast({
              title: res.data.resultMessage,
              icon: 'none'
            })
            this.loginForm.user_no = this.loginForm.user_no
            this.loginForm.pwd = this.loginForm.rpwd;
            this.loginType = '账号登录'
            this.changeDialogType('successReset')
          } else {
            uni.showToast({
              title: res.data.resultMessage,
              icon: 'none'
            })
          }
        })
      },
      // 校验手机验证码
      async verifyPhoneCode() {
        if (!this.code) {
          uni.showToast({
            title: '请输入验证码',
            icon: 'none'
          })
          return
        }
        const url = `/sso/operate/srvsso_check_mobile`
        const req = [{
          "serviceName": "srvsso_check_mobile",
          "data": [{
            "mobile": this.loginForm.user_no,
            "mobile_code": this.code
          }]
        }]
        const res = await this.$http.post(url, req)
        if (res?.data?.state === 'SUCCESS') {
          // 短信验证码校验成功，打开重置密码弹框
          this.changeDialogType('resetPwd')
        } else {
          uni.showToast({
            title: res?.data?.resultMessage,
            icon: 'none'
          })
        }
      },
      changeDialogType(e) {
        this.dialogType = e
        if (e !== 'login') {
          // if (e === 'findPwd' || e === 'resetPwd') {
          this.loginForm.npwd = "" // 新密码
          this.loginForm.rpwd = "" // 重复输入新密码
          this.loginForm.user_no = "" //账号 手机号
          this.loginForm.pwd = "" // 密码
        } else {

        }
      },
      changePassword() {
        this.showPassword = !this.showPassword;
      },
      // 切换登录方式
      changeLoginType(e) {
        this.loginType = e
        if (e === '账号登录') {
          let loginForm = uni.getStorageSync('loginForm')
          if (loginForm?.user_no) {
            this.loginForm = loginForm
            this.isRemember = ['是']
          }
        } else if (e === '手机登录') {
          this.loginForm.user_no = ''
        }
      },
      async toLogin() {
        if (this.saveLoginForm?.user_no && this.saveLoginForm?.user_no !== this.loginForm.user_no) {
          uni.clearStorageSync()
        }
        let tenant = `${this.loginForm.tenant}`
        if (!tenant) {
          uni.showToast({
            title: '请输入商家编号',
            icon: 'none'
          })
          return
        } else if (tenant.length < 4) {
          uni.showToast({
            title: '商家编号长度必须大于4位',
            icon: 'none'
          })
          return
        } else if (tenant.length > 16) {
          uni.showToast({
            title: '商家编号长度必须小于16位',
            icon: 'none'
          })
          return
        }
        if (this.loginType === '账号登录') {
          if (!this.loginForm.user_no) {
            uni.showToast({
              title: '请输入手机号',
              icon: 'none'
            })
            return
          }
          if (!this.loginForm.pwd) {
            uni.showToast({
              title: '请输入密码',
              icon: 'none'
            })
            return
          }
          if (this.needImageCode) {
            if (!this.imageCode) {
              uni.showToast({
                title: '请输入图形验证码',
                icon: 'none'
              })
            } else {
              let isTrue = await this.validImageCode()
              if (!isTrue) {
                return
              }
            }
          }
          this.accountLogin()
        } else {
          this.verifyPhone().then(res => {
            if (res === true) {
              this.mobileLogin()
            } else {
              uni.showToast({
                title: '当前手机号未注册账号',
                icon: 'none'
              })
            }
          })
        }
      },
      // 获取验证码
      getCode() {

        if (this.loginType == '手机登录') {
          if (!/^1\d{10}$/.test(this.loginForm.user_no)) {
            // if (!/^1(1|2|3|4|5|6|7|8|9)\d{9}$/.test(this.loginForm.user_no)) {
            return uni.showToast({
              icon: 'error',
              title: '请输入正确的手机号'
            })
          }
        }

        const url = `/sso/operate/srvsso_send_node`
        const req = [{
          "serviceName": "srvsso_send_node",
          "data": [{
            "mobile": this.loginForm.user_no,
            "type": this.dialogType == 'login' ? "login" : "cfp"
          }]
        }]

        if (this.loginForm.user_no) {
          this.$http.post(url, req).then(res => {
            this.canSendCode = false
            let interVal = setInterval(() => {
              this.outTime--
            }, 1000)
            setTimeout(() => {
              this.canSendCode = true
              this.outTime = 60
              clearInterval(interVal)
            }, 60 * 1000)
            if (res?.data?.state === 'SUCCESS') {
              uni.showToast({
                title: '验证码发送成功,请注意查收',
                icon: 'none'
              })
            } else {
              uni.showToast({
                title: res?.data?.response[0]?.response?.msg || res.data.resultMessage,
                icon: 'none'
              })
            }

          })
        } else {
          uni.showToast({
            title: '请输入手机号码',
            icon: 'none'
          })
        }

      },
      //手机号+验证码登录
      mobileLogin() {
        if (!this.loginForm.user_no) {
          uni.showToast({
            title: '请输入手机号',
            icon: 'none'
          })
          return
        }
        if (!this.code) {
          uni.showToast({
            title: '请输入短信验证码',
            icon: 'none'
          })
          return
        }
        if (!this.loginForm.tenant) {
          uni.showToast({
            title: '请输入商户号',
            icon: 'none'
          })
          return
        }
        let tenant = this.loginForm.tenant;
        tenant = Number(tenant)
        const url = `/sso/operate/srvsso_mobile_note_login`
        const req = [{
          "serviceName": "srvsso_mobile_note_login",
          "data": [{
            "mobile": this.loginForm.user_no,
            "code": this.code,
            "terminal_type": "mt",
            'tenant': tenant,
          }]
        }]
        this.$http.post(url, req).then(res => {
          console.log(res);
          if (res?.data?.state === 'SUCCESS') {
            this.handlerLoginData(res)
          } else if (res?.data?.resultMessage) {
            uni.clearStorageSync()
            uni.showToast({
              title: res?.data?.resultMessage,
              icon: 'none'
            })
          }
        })
      },
      // 处理登录后后端返回的数据
      handlerLoginData(res) {
        // 登录成功
        this.$store.commit('SET_LOGIN_STATE', true)
        if (Array.isArray(res?.data?.response)) {
          uni.setStorageSync('start_time', this.dayjs().format("YYYY-MM-DD HH:mm:ss"))
          let {
            response
          } = res?.data?.response[0]
          if (response?.bx_auth_ticket) {
            uni.setStorageSync('bx_auth_ticket', response.bx_auth_ticket)
            this.$store.commit('SET_TICKET', response.bx_auth_ticket)
          }
          if (response?.login_user_info) {
            if (Array.isArray(response?.login_user_info?.tenantInfos) && response?.login_user_info?.tenantInfos
              .length >
              0 && response?.login_user_info?.tenantInfos[0]?.tenant_no) {
              response.login_user_info._tenant_info = response?.login_user_info?.tenantInfos[0]
            }
            uni.setStorageSync('login_user_info', response.login_user_info)
            this.$store.commit('SET_LOGIN_USER', response.login_user_info)
          }
        }

        getUserMenus()
        uni.reLaunch({
          url: '/pages/main/cash/cash'
        })


      },
      // 账号登录
      async accountLogin() {
        let tenant = this.loginForm.tenant;
        tenant = Number(tenant)
        const req = [{
          "serviceName": "srvuser_login",
          "data": [{
            "user_no": this.loginForm.user_no,
            "pwd": this.loginForm.pwd,
            'tenant': tenant,
            "terminal_type": "mt",
          }]
        }]
        const url = `/sso/operate/srvuser_login`
        uni.showLoading({})
        console.log(req);
        const res = await this.$http.post(url, req)
        uni.hideLoading()
        if (res?.data?.state === 'SUCCESS') {
          this.needImageCode = false
          this.handlerLoginData(res)
          if (Array.isArray(this.isRemember) && this.isRemember.includes('是')) {
            uni.setStorageSync('loginForm', this.loginForm)
          } else {
            uni.setStorageSync('loginForm', '')
          }
          uni.setStorageSync('start_time', this.dayjs().format("YYYY-MM-DD HH:mm:ss"))
        } else {
          if (res.data?.resultCode === '6666' || res.data?.resultCode === 'FAILURE') {
            this.needImageCode = true
            this.getImageCode()
          }
          uni.showToast({
            title: res?.data?.resultMessage,
            icon: 'none'
          })
        }

      },

    }
  }
</script>

<style lang="scss" scoped>
  .login-wrap {
    background-image: url('../../../static/images/login_bg.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    width: 100vw;
    height: calc(100vh - var(--window-top) - var(--window-bottom));
    overflow: hidden;
    // padding-top: 12.7rem;
    display: flex;
    justify-content: center;
    align-items: center;

    .login-dialog {
      margin: 0 auto;
      width: 75rem;
      min-height: 78.3rem;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 4.7rem 0 5rem;
      background-color: #fff;
      border-radius: 5rem;

      .tips {
        text-align: center;
        margin: 2rem;
        color: #A6A6A6;
        font-size: $retail-font-size-sm;
      }

      .title {
        font-size: 4.2rem;
        line-height: 6rem;
        margin-bottom: 1.8rem;
        font-weight: 700;
      }

      .tab-list {
        display: flex;
        font-size: 3.2rem;
        width: 100%;
        padding: 0 3rem;
        padding: 0 10rem;

        .tab-item {
          flex: 1;
          text-align: center;
          padding: 1rem;
          border-bottom: .5rem solid #fff;

          &.active {
            color: $retail-color-primary;
            border-color: $retail-color-primary;
          }
        }
      }

      .input-box {
        flex: 1;
        padding: 0 10rem;

        .input-item {
          display: flex;
          align-items: center;
          width: 52.4rem;
          height: 8rem;
          margin-top: 2rem;
          border-radius: 1.2rem;
          border: 1px solid #E5E5E5;
          font-size: 4rem;
          padding-left: 3rem;
          color: $retail-color-primary;

          .image-code {
            width: 18rem;
            height: 8rem;
          }

          .uni-easyinput {
            height: 100%;

            ::v-deep .uni-easyinput__content {
              height: 100%;

              .uni-input-wrapper {
                font-size: 2.4rem;
                line-height: 3rem;
              }

              .uni-easyinput__placeholder-class {
                font-size: 2.4rem;
                line-height: 3rem;
              }
            }
          }

          .label {
            font-size: $retail-font-size-sm;
            color: #333;
          }

          .input {
            margin-left: 3rem;
            font-size: $retail-font-size-sm;
            flex: 1;
            color: #666;

            &.text-right {
              text-align: right;
            }
          }
        }
      }

      .check-box-bar {
        padding: 0 10rem;
        width: 100%;
        padding: 2rem;
        font-size: $retail-font-size-sm;
        padding: 2rem 10rem;

        ::v-deep .u-checkbox__icon-wrap {
          margin-right: 1.3rem;
        }

      }

      .tip-bar {
        // padding:  0 10rem;
        padding: 2rem 0 3rem;
        font-size: 2rem;
      }

      .button-bar {
        padding: 0 10rem;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .uni-eye {
    color: #999;

    &-active {
      color: $retail-color-primary;
    }
  }
</style>
